package com.intco.ait.quotation.api.starter.web;

import com.intco.ait.quotation.api.common.model.BaseResponse;
import com.intco.ait.quotation.api.common.model.BomVo;
import com.intco.ait.quotation.api.common.model.request.BomSearch;
import com.intco.ait.quotation.api.infrastructure.mybatis.entity.BomTemplateDo;
import com.intco.ait.quotation.api.infrastructure.service.BomService;
import com.intco.ait.quotation.api.starter.advice.LocalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/bom")
@Slf4j
public class BomController {

    @Autowired
    private BomService bomService;

    @PostMapping("/search")
    public BaseResponse<?> getBomList(@RequestBody BomSearch bomSearch) {
        try {
            return BaseResponse.success(bomService.search(bomSearch));
        } catch (Exception e) {
            log.error("getBomList调用失败", e);
            throw new LocalException(500, "查询失败:".concat(e.getMessage()), e);
        }
    }

    public BaseResponse<?> getBomDetail() {
        return BaseResponse.success();
    }

    @PostMapping("/add")
    public BaseResponse<?> createBom(@RequestBody BomVo bomVo) {
        try {
            BomTemplateDo bomTemplateByName = bomService.getBomTemplateByName(bomVo.getName());
            if (bomTemplateByName != null) {
                return BaseResponse.fail(bomTemplateByName.getId(), "Bom exists with the same name");
            }
            return BaseResponse.success(String.valueOf(bomService.creatBom(bomVo)), "");
        } catch (Exception e) {
            log.error("createBom调用失败", e);
            throw new LocalException(500, "新增失败:".concat(e.getMessage()), e);
        }
    }

    @PostMapping("/edit")
    public BaseResponse<?> updateBom(@RequestBody BomVo bomVo) {
        try {
            bomService.updateBom(bomVo);
            return BaseResponse.success();
        } catch (Exception e) {
            log.error("updateBom调用失败", e);
            throw new LocalException(500, "修改失败:".concat(e.getMessage()), e);
        }
    }

}
